<script>
import { queryCartCount } from "@/lib/api/interestedServer/cart";
import { mapState, mapMutations, mapActions } from "vuex";
export default {
	data() {
		return {
			animationData: {}
		};
	},
	computed: {
		...mapState("tabbar", ["tabList", "currentTabIndex"])
	},

	onLoad() {
		uni.hideTabBar();
		const curPages= getCurrentPages();
		const curPage = curPages[curPages.length - 1];
		if((curPage.route === "pages/tabbar/category")||(curPage.route === "pages/tabbar/cart")){
			uni.setNavigationBarColor({
				frontColor: "#ffffff",
				backgroundColor: this.themeStyles.mainColor
			});
		}
	},

	onShow() {
		const pages = getCurrentPages();
		const currentPagePath = "/" + pages[pages.length - 1].route;

		this.updateCurrentTabIndex(null);

		this.tabList.forEach((item, index) => {
			if (item.pagePath == currentPagePath) {
				this.updateCurrentTabIndex(index);
			}
		});
		this.getCartCount();

		setTimeout(() => {
			var animation = uni.createAnimation({
				duration: 200,
				timingFunction: "ease"
			});

			this.animation = animation;

			animation
				.scale(1.15, 1.15)
				.rotate(0)
				.step();

			this.animationData = animation.export();
		}, 150);
	},

	onHide() {
		this.animation
			.rotate(0)
			.scale(1, 1)
			.step();
		this.animationData = this.animation.export();
	},

	onPullDownRefresh() {
		this.getCartCount();
	},

	methods: {
		...mapMutations("tabbar", [
			"updateCurrentTabIndex",
			"updateTabBarList"
		]),

		switchTabbar(index, tabList) {
			if (this.currentTabIndex === index) {
				this.animation
					.rotate(0)
					.scale(0.4, 0.4)
					.step();
				this.animationData = this.animation.export();

				setTimeout(() => {
					this.animation
						.rotate(0)
						.scale(1.15, 1.15)
						.step();
					this.animationData = this.animation.export();
				}, 150);

				uni.pageScrollTo({
					scrollTop: 0,
					duration: 400
				});
				return;
			}
			this.switchTo(tabList[index].pagePath);
		},

		// 查询购物车数量
		async getCartCount() {
			try {
				const res = await queryCartCount({
					showLoading: false
				});
				const badge = res.data;

				if (badge > 0) {
					if (this.tabList[2].badge === badge) return;

					this.tabList[2].badge = badge;
					//   uni.setTabBarBadge({
					//     index: 2,
					//     text: `${badge}`
					//   });
				} else {
					this.tabList[2].badge = null;
					//   uni.removeTabBarBadge({
					//     index: 2
					//   });
				}

				this.updateTabBarList(this.tabList);
			} catch (error) {
				console.log("error", error);
			}
		}
	}
};
</script>